package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrdersettingService;
import com.itheima.utils.POIUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/ordersetting")

public class OrdersettingController {
    @Reference
    private OrdersettingService ordersettingService;

    //导入预约信息
    @RequestMapping("/upload")
    public Result add(@RequestParam("excelFile") MultipartFile excelFile){
        try {
            //调用工具类，得到前端传过来的文件数据
            List<String[]> strings = POIUtils.readExcel(excelFile);
            //设置一个集合，用来添加封装好的数据
            List<OrderSetting> list = new ArrayList<>();
            //遍历从前端传过来的数据
            for (String[] string : strings) {
                //得到时间
                String orderDate = string[0];
                //得到可预约人数
                String number = string[1];
                //添加到预约信息这个实体类中
                OrderSetting orderSetting = new OrderSetting(new Date(orderDate) , Integer.parseInt(number));
                //将这个实体类添加到前面设置的list集合
                list.add(orderSetting);
                ordersettingService.add(list);
            }
            return new Result(true , MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false , MessageConstant.IMPORT_ORDERSETTING_FAIL);
        }
    }

    //将导入到数据库的预约信息显示到前端
    @RequestMapping("/getOrdersettingByMonth")
    public Result getOrdersettingByMonth(String date){
        try {
            List<Map> list = ordersettingService.getOrdersettingByMonth(date);
            return new Result(true , MessageConstant.GET_ORDERSETTING_SUCCESS , list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.GET_ORDERSETTING_FAIL);
        }
    }

    //设置预约人数
    @RequestMapping("/setNumberByDate")
    public Result setNumberByDate(@RequestBody OrderSetting orderSetting){
        try {
            ordersettingService.setNumberByDate(orderSetting);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false , MessageConstant.ORDERSETTING_FAIL);
        }
        return new Result(true , MessageConstant.ORDERSETTING_SUCCESS);
    }
}
